package com.gitee.kamismile.stoneComEx.util;

import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import org.apache.commons.collections.MapUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: lidong
 * Date: 12-9-1
 * Time: 下午2:05
 * To change this template use File | Settings | File Templates.
 */
public class MapUtil extends MapUtils {

    public static Map<String, Object> supplementary(Map<String, Object> map1, Map<String, Object> map2) {
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.putAll(map1);
        Set<String> key2 = map2.keySet();
        Iterator<String> it = key2.iterator();

        while (it.hasNext()) {
            map3.remove(it.next());
        }
        return map3;
    }

    public static <T> T copyBySerialize(T map) throws Exception {

        try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
             ObjectOutputStream out = new ObjectOutputStream(byteOut);
        ) {
            out.writeObject(map);
            try (ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
                 ObjectInputStream in = new ObjectInputStream(byteIn)) {
                return (T) in.readObject();
            }
        }
    }


    public static void plusObjectValue(Map<String, Object> map, String key, Object value) {
        if (map.containsKey(key)) {
            if (value instanceof Double) {
                Double oldValue = (Double) map.get(key);
                map.put(key, ValueUtils.add(oldValue, (Double) value));
            } else if (value instanceof Long) {
                Long oldValue = (Long) map.get(key);
                map.put(key, oldValue + (Long) value);
            } else if (value instanceof Integer) {
                Integer oldValue = (Integer) map.get(key);
                map.put(key, oldValue + (Integer) value);
            }
        } else {
            map.put(key, value);
        }
    }
}
